#include <QtUiTools>
#include <QtGui>
#include "SchedulePlanner.h"

SchedulePlanner::SchedulePlanner(QWidget *parent)
    : QWidget(parent)
{
    QWidget *formWidget = loadUiFile();

    ui_Button = qFindChild<QPushButton*>(this, "Button");
    ui_textEdit = qFindChild<QTextEdit*>(this, "textEdit");
    ui_lineEdit = qFindChild<QLineEdit*>(this, "lineEdit");


    ui_textEdit->setReadOnly(true);

    QMetaObject::connectSlotsByName(this);

    this->setup(formWidget);

    noFileNameYet = true;
    isFirstTime = true;
    anotherInput = ERROR;
}

void SchedulePlanner::setup(QWidget* formWidget)
{
    QVBoxLayout *layout = new QVBoxLayout;
    layout->addWidget(formWidget);
    this->setLayout(layout);
    this->setWindowTitle(tr("Schedule Planner"));
}

QWidget* SchedulePlanner::loadUiFile()
{
    QUiLoader loader;

    QFile file(":/SchedulePlanner.ui");
    file.open(QFile::ReadOnly);

    QWidget *formWidget = loader.load(&file, this);
    file.close();

    return formWidget;
}


void SchedulePlanner::on_Button_clicked()
{
    QString searchString = ui_lineEdit->text();

    //QMessageBox::information(this,tr("Adding"),searchString);
    if(searchString == "exit"){
        close();
    }else if(noFileNameYet)
    {
        string fileName = fromQstringToString(searchString);
        parser.init_storage(fileName);
        noFileNameYet = false;

        ui_textEdit->append("The file name is initialized as ");
        ui_textEdit->append(searchString);

    } else if(anotherInput == ERROR){
        string userInput = fromQstringToString(searchString);
        O = parser.run(userInput);
        anotherInput = O.next_inputtype;

        //printMessage
        int outputSize = O.output_strings.size();
        for(int i=0;i<outputSize;i++)
        {
            QString qstr = fromStringToQstring(O.output_strings[i]);
            ui_textEdit->append(qstr);
        }

    } else{
        anotherInput = ERROR;
        string userInput = fromQstringToString(searchString);
        int choice = atoi(userInput.c_str());
        O = parser.anotherinput(choice, O.next_inputtype);
    }

    ui_lineEdit->setText("");
    parser.clear_logic_containers();

}

string SchedulePlanner::fromQstringToString(QString qstr)
{
    string str = qstr.toStdString();
    return str;
}

QString SchedulePlanner::fromStringToQstring(string str)
{
    QString qstr = QString::fromStdString(str);
    return qstr;
}
